﻿using NetService.Define;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace NetService.Service
{
    public class IPService
    {
        /*
         * \brief IP信息汇总
         * 
         * \param  IPAddress  IP地址信息
         */
        private IPData GetIPData(string IPAddress)
        {
            IPData ipData = new IPData();
            //判断是否输入了主机地址
            if (IPAddress == string.Empty)
            {
                MessageBox.Show("请输入主机地址!");
            }
            else
            {
                //获取指定主机的IP地址
                IPAddress[] ips = Dns.GetHostAddresses(IPAddress);
                //循环访问获得的IP地址
                foreach (IPAddress ip in ips)
                {
                   // ipData.IPAddress = ip.ToString();//将得到的IP地址显示在文本框中
                }
                ipData.HostName = Dns.GetHostName();//获取本机名
                //根据指定的主机名获取DNS信息
                ipData.DNSHostByName = Dns.GetHostByName(Dns.GetHostName()).HostName;
            }
            return ipData;
        }

        /*
         * \brief IP信息转换
         * 
         * \param  IPAddress  IP地址信息
         */
        private string GetIPMessage(string address, int port)
        {
            //实例化IPEndPoint类对象
            IPEndPoint IPEPoint = new IPEndPoint(IPAddress.Parse(address), port);
            //使用IPEndPoint类对象获取终结点的IP地址和端口号
            string IPMessage= "IP地址：" + IPEPoint.Address.ToString() + "\n端口号：" + IPEPoint.Port;
            return IPMessage;
        }

        /*
         * \brief 获取对应网址内容
         * 
         * \param  baseAddress  IP地址信息
         */
        private string GetWebData(string baseAddress)
        {
            string getWebData = string.Empty;
            WebClient wclient = new WebClient();　　　　　　　//实例化WebClient类对象
            wclient.BaseAddress = baseAddress;　　　　　　　//设置WebClient的基URI
            wclient.Encoding = Encoding.UTF8;                 //指定下载字符串的编码方式
            //为WebClient类对象添加标头
            wclient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            //使用OpenRead方法获取指定网站的数据，并保存到Stream流中
            Stream stream = wclient.OpenRead(baseAddress);
            //使用流Stream声明一个流读取变量sreader
            StreamReader sreader = new StreamReader(stream);
            string str = string.Empty;//声明一个变量，用来保存一行从WebCliecnt下载的数据
            //循环读取从指定网站获得的数据
            while ((str = sreader.ReadLine()) != null)
            {
                getWebData += str + "\n";
            }
            //调用WebClient对象的DownloadFile方法将指定网站的内容保存到文件中
            wclient.DownloadFile(baseAddress, DateTime.Now.ToFileTime() + ".txt");
            MessageBox.Show("保存到文件成功");
            return getWebData;
        }



        /// <summary>
        /// 得到本机IP
        /// </summary>
        private string GetLocalIP()
        {
            //本机IP地址
            string strLocalIP = String.Empty;
            //得到计算机名
            string strPcName = Dns.GetHostName();
            //得到本机IP地址数组
            IPHostEntry ipEntry = Dns.GetHostEntry(strPcName);
            //遍历数组
            foreach (var IPadd in ipEntry.AddressList)
            {
                //判断当前字符串是否为正确IP地址
                if (IsRightIP(IPadd.ToString()))
                {
                    //得到本地IP地址
                    strLocalIP = IPadd.ToString();
                    //结束循环
                    break;
                }
            }

            //返回本地IP地址
            return strLocalIP;
        }


        /**
         * 判断是否为正确的IP地址
         *
         *<param name="strIPadd">需要判断的字符串</param>
         * <returns>true = 是 false = 否</returns>
         */
        public static bool IsRightIP(string strIPadd)
        {
            //利用正则表达式判断字符串是否符合IPv4格式
            if (Regex.IsMatch(strIPadd, "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"))
            {
                //根据小数点分拆字符串
                string[] ips = strIPadd.Split('.');
                if (ips.Length == 4 || ips.Length == 6)
                {
                    //如果符合IPv4规则
                    if (System.Int32.Parse(ips[0]) < 256 && System.Int32.Parse(ips[1]) < 256 & System.Int32.Parse(ips[2]) < 256 & System.Int32.Parse(ips[3]) < 256)
                        //正确
                        return true;
                    //如果不符合
                    else
                        //错误
                        return false;
                }
                else
                    //错误
                    return false;
            }
            else
                //错误
                return false;
        }

        //得到网关地址
        private string GetGateway()
        {
            //网关地址
            string strGateway = "";
            //获取所有网卡
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            //遍历数组
            foreach (var netWork in nics)
            {
                //单个网卡的IP对象
                IPInterfaceProperties ip = netWork.GetIPProperties();
                //获取该IP对象的网关
                GatewayIPAddressInformationCollection gateways = ip.GatewayAddresses;
                foreach (var gateWay in gateways)
                {
                    //如果能够Ping通网关
                    if (IsPingIP(gateWay.Address.ToString()))
                    {
                        //得到网关地址
                        strGateway = gateWay.Address.ToString();
                        //跳出循环
                        break;
                    }
                }

                //如果已经得到网关地址
                if (strGateway.Length > 0)
                {
                    //跳出循环
                    break;
                }
            }

            //返回网关地址
            return strGateway;
        }

        /// <summary>
        /// 尝试Ping指定IP是否能够Ping通
        /// </summary>
        /// <param name="strIP">指定IP</param>
        /// <returns>true 是 false 否</returns>
        public static bool IsPingIP(string strIP)
        {
            try
            {
                //创建Ping对象
                Ping ping = new Ping();
                //接受Ping返回值
                PingReply reply = ping.Send(strIP, 1000);
                //Ping通
                return true;
            }
            catch
            {
                //Ping失败
                return false;
            }
        }

    }


}
